package cn.gov.msa.aop;

import java.lang.reflect.Method;
import java.util.List;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Component;

import cn.gov.msa.model.UserRole;
import cn.gov.msa.service.UserDetailService;
import cn.gov.msa.util.DZZWCacheEvict;
import cn.gov.msa.util.DefaultKeyGenerator;

/**
  * 
  * @ClassName: CacheAspect  
  * @Description: 自定义注解切面 
  * @author lee  
  * @date 2018年6月19日  
  *
  */
@Aspect
@Component
public class CacheAspect{
	
	@Autowired
    CacheManager cacheManager;
	@Autowired
	private DefaultKeyGenerator defaultKeyGenerator;
	@Autowired
	private UserDetailService userDetailService;
	
	@Pointcut("@annotation(cn.gov.msa.util.DZZWCacheEvict)")
	public void annotationPointCut() {}
	 
	  @After("annotationPointCut()")
      public void after(JoinPoint joinpoint) throws Exception{
          MethodSignature signature = (MethodSignature) joinpoint.getSignature();
          Method method = signature.getMethod();
          DZZWCacheEvict myCacheEvict = method.getAnnotation(DZZWCacheEvict.class);
          //反射得到注解上的属性
          String value = myCacheEvict.value();
          String key = myCacheEvict.key();
  		  Cache cache = cacheManager.getCache(value);
  		  
          String roleCode =  defaultKeyGenerator.generateKey(joinpoint, value, key);    
          UserRole userRole = new UserRole();
          userRole.setRolecode(roleCode);
          List<UserRole> users = userDetailService.selectUserRole(userRole);
          if(users.size()>0) {
        	  for (int i = 0; i < users.size(); i++) {
				UserRole user = users.get(i);
				String evictKey = "queryLeftMenu"+user.getUserid();
			    cache.evict(evictKey);
			}
          }
      }
      @Before("annotationPointCut()")
      public void before(JoinPoint joinpoint){

      }
	
}
